var express = require("express");
var router = express.Router();
const userService = require("../service/userService");
const { parseJwt } = require("../utils/tools");

// 注册
router.post("/register", async (req, res, next) => {
  const { data, message } = await userService.register(req.body);
  if (data) {
    res.sendRes({
      data,
    });
  } else {
    res.sendErr({
      message: "用户已存在",
    });
  }
});

// 登录
router.post("/login", async (req, res, next) => {
  const { data, message } = await userService.login(req.body);
  if (data && data.token) {
    res.setHeader("Authorization", data.token);
    res.sendRes({
      data,
    });
  } else {
    res.sendErr({
      message,
    });
  }
});

// 获取用户信息
router.get("/userInfo", async (req, res, next) => {
  const token = req.get("Authorization");
  const tokenData = parseJwt(token)
  console.log('打印tokenData：', tokenData.data)
  const { data, message } = await userService.getUserInfo(tokenData.data.userId);
  if (data) {
    res.sendRes({
      data,
    });
  } else {
    res.sendErr({
      message,
    });
  }
});

router.post("/loginOut", userService.loginOut);

module.exports = router;
